<?php

namespace app\index\controller;

use app\common\controller\Front;
use think\Db;

/**
 * 文章
 * Class Article
 * @package app\index\controller
 */
class Article extends Front
{

    protected function _initialize()
    {
        parent::_initialize();

        $cate = model('Category')->where(['model_id' => 1])->field('id, name, title')->select();
        $this->assign('cate', $cate);
    }

    public function index()
    {
        $this->redirect(url('lists', ['cid' => 1], true, true));
    }

    public function lists($cid = 0)
    {
        if ($cid <= 0) $this->redirect('/');

        $title = model('Category')->where(array('id' => $cid))->value('title');
        if (empty($title)) $this->redirect('/');

        $this->assign('cate_name', $title);
        $list = model('Article')->where(['category_id' => $cid])->paginate(10, $this->isMobile(), $this->request->param());

        $this->assign('cid', $cid);
        $this->assign('list', $list);
        $this->assign('page', $list->render());

        return $this->fetch();
    }

    public function detail($id = 0)
    {
//        $id = $this->request->param('id');
        if (!$id) $this->redirect('/');

//        $max_id = Db::name('article')->max('id');
//        if ($id > $max_id) {
//            $this->redirect('/');
//            exit;
//        }
//
//        if (preg_match('/^\/article\/detail\/id\/(\d+).html$/', $_SERVER['REQUEST_URI'])) {
//            $this->redirect(url('/index/article/' . $id, '', true, true));
//        }

        $article = model('Article')->where(['id' => $id])->find();
        if (empty($article)) $this->redirect('/');

//        $article['art_info'] = cnsubstr(strip_tags($article['art_content']), 80, 0, "utf-8", true, '...');

        $this->assign('cate_name', model('Category')->where(['id' => $article['category_id']])->value('title'));

        $this->assign('cid', $article['category_id']);
        $this->assign('article', $article);
        return $this->fetch();
    }
}